package com.study.amqp_2;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class SimpleConsumer {

	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

		ConnectionFactory factory = new ConnectionFactory();

		factory.setHost("127.0.0.1");
		factory.setPort(5672);
		factory.setUsername("guest");
		factory.setVirtualHost("log");

		Connection conn = factory.newConnection();
		Channel channel = conn.createChannel();

		// TODO 消費消息,第二個參數設置true，自動設置消息已經被可靠消費了,ctrl+t查看一個類的層次，選擇繼承Consumer的實現類DefaultConsumer
		channel.basicConsume("q1", true, new DefaultConsumer(channel) {

			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				System.out.println("------消息tag------"+consumerTag);
				System.out.println("---------消費body-------"+new String(body));
				//envelope.getExchange();
				//envelope.getRoutingKey();
				
				System.out.println(envelope.getDeliveryTag());
			}

		});
		
		//暫停20seconds 可以在rabbitMQ管理面板queue的Consumers中查看到消費者的標籤
		TimeUnit.SECONDS.sleep(20);

		channel.close();
		conn.close();

	}

}
